package me.crawler;
public class CrawlerThreadController {

	int level;
	int maxLevel;
	int maxThreads;
	URLQueue tasks;
	int counter;
	int nThreads;


	public CrawlerThreadController(int _maxThreads,int _maxLevel,URLQueue _tasks,int _level)
		throws InstantiationException, IllegalAccessException {
		maxThreads = _maxThreads;
		maxLevel = _maxLevel;
		tasks = _tasks;
		level = _level;
		counter = 0;
		nThreads = 0;
		startThreads();
	}

	public synchronized int getUniqueNumber() {
		return counter++;
	}


	public synchronized void setMaxThreads(int _maxThreads)
		throws InstantiationException, IllegalAccessException {
		maxThreads = _maxThreads;
		startThreads();
	}


	public int getMaxThreads() {
		return maxThreads;
	}

	public int getMaxLevel() {
		return maxLevel;
	}


	public int getRunningThreads() {
		return nThreads;
	}


	public synchronized void finished(int threadId) {
		nThreads--;
		if (nThreads == 0) {
			level++;
			if (level > maxLevel) {
				return;
			}

			if (tasks.getQueueSize(level) == 0) {
				
				return;
			}
			try {
				startThreads();
			} catch (InstantiationException e) {
			} catch (IllegalAccessException e) {
			}
		}
	}


	public synchronized void startThreads()
		throws InstantiationException, IllegalAccessException {

		int max = maxThreads - nThreads;
		int ts = tasks.getQueueSize(level);
		if (ts < max || maxThreads == -1) {
			max = ts;
		}
		for (int n = 0; n < max; n++) {
			CrawlerThread thread = new CrawlerThread();
			thread.setThreadController(this);
			thread.setLevel(level);
			thread.setQueue(tasks);
			thread.setId(nThreads++);
			thread.start();
		}
	}
}
